/* 
 * Copyright 2013 Sébastien Mouquet.
 * 
 * This file is part of ECovoiturage.
 * 
 * ECovoiturage is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ECovoiturage is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Foobar. If not, see http://www.gnu.org/licenses/.
 */
package com.smouquet.ecovoiturage.core.dao.impl;

import com.google.inject.Inject;
import com.smouquet.ecovoiturage.core.dao.DAO;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;

/**
 *
 * @author sebastien.mouquet
 */
public class DAOImpl<T, PK extends Serializable> implements DAO<T, PK>
{
    protected Class<T> type;
    
    @Inject
    private EntityManager em;
    
    public DAOImpl()
    {
        ParameterizedType paramType = (ParameterizedType)getClass().getGenericSuperclass();
        this.type = (Class<T>)paramType.getActualTypeArguments()[0];
    }
    
    protected EntityManager em()
    {
        return this.em;
    }
    

    @Override
    public void persist(T entity)
    {
        em().persist(entity);
    }

    @Override
    public T getReference(PK id)
    {
        try
        {
            return em().getReference(type, id);
            
        } catch(EntityNotFoundException ex) {
            return null;
        }
    }

    @Override
    public void refresh(T entity)
    {
        em().refresh(entity);
    }

    @Override
    public T merge(T entity)
    {
        return em().merge(entity);
    }

    @Override
    public void remove(T entity)
    {
        T e = em().merge(entity);
        em().remove(e);
    }
    
}
